package proxyhelper

import (
	"fmt"
	"io"
	"iptv_server/v3/v2_src/utils"
	"net/http"
	"net/url"
)

func New_fallback_redirect2fileServer() *Fallback_redirect2fileServer {

	return &Fallback_redirect2fileServer{}
}

type Fallback_redirect2fileServer struct {
	// client       *http.Client
	// url          url.URL
	// fallbackPort int
}

func (h *Fallback_redirect2fileServer) Redirect(u *url.URL, client *http.Client, fallbackPort int, w http.ResponseWriter) {
	utils.Logger.Debugf("proxy fallback_redirect2fileServer:path=%v", u)

	u.Host = fmt.Sprintf("127.0.0.1:%d", fallbackPort)

	resp, err := client.Get(u.String())
	if err != nil {
		utils.Logger.Debugf("proxy err:%v", err)
		w.WriteHeader(http.StatusNotFound)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusNotFound {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	w.Header().Add(utils.HeaderKeyContentType, resp.Header.Get(utils.HeaderKeyContentType))
	io.Copy(w, resp.Body)

}
